﻿$().ready(function () {
    $("#optInventoryItem").attr("class", "HoverOnList");
    $("#breadcrumb").append('<li><a href="' + $("#urlInventoryItem").val() + '" title="Pedidos de Inventario">Pedidos de Iventario</a></li>');


    var validator1 = $("#frmInventoryOrders").bind("invalid-form.validate", function () {
        //$("#lblError").show();
    }).validate({
        debug: true,
        rules: {
            productLocationID: {
                required: true,
                minlength: 1
            },
        },
        messages: {
            productLocationID: "La localización del producto es requerida"
        }
    });

    $('.item-del').live('click', function () {
        if (confirm('¿Esta seguro que desea eliminar el registro?')) {
            $(this).closest('li').remove();
        }
    });

    ///Toolbar
    $('#btnClear').live('click', function () {
        ClearForm();
    });

    $("#txtQuantity").spinner({
        min: 0,
        step: 1,
        start: 0,
        numberFormat: "n"
    });

    $('#btnNew').live('click', function () {
        if (confirm('¿Desea abandonar la edición y crear un registro nuevo?')) {
            window.location = $('#urlCreate').val();
        }
    });

    ///Menu
    $('#menuClear').live('click', function () {
        ClearForm();
    });

    $('#menuNew').live('click', function () {
        if (confirm('¿Desea abandonar la edición y crear un registro nuevo?')) {
            window.location = $('#urlCreate').val();
        }
    });
    $('#btnSearch').click(function () {
        Search();
    });

    $('#btnAdd').click(function () {
        AddRecord();
    });


    $("#txtStartDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtEndDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $('#btnSaveMenu').click(function () {
        if ($("#frmInventoryOrders").valid()) {

            var list = new Array();
            $('#lstInventoryOrders li').each(function () {
                var current = $(this);
                var item = current.attr("productid") + ";" + current.attr("quantity");
                list.push(item);
            });

            if (list.length > 0) {
                Add();
            }
            else {
                alert('Debe ingresar al menos un producto al listado');
            }
        }
    });

    $('#btnSave').click(function () {
        if ($("#frmInventoryItem").valid()) {

            var list = new Array();
            $('#lstInventoryOrders li').each(function () {
                var current = $(this);
                var item = current.attr("productid") + ";" + current.attr("quantity");
                list.push(item);
            });

            if (list.length > 0) {
                Add();
            }
            else {
                alert('Debe ingresar al menos un producto al listado');
            }
        }
    });


   
    if (!(typeof $('#txtItemFilter')[0] === "undefined")) {
        InitAutocomplete();
    }
});

function ConfirmDelete(id) {
    if (confirm('¿Esta seguro que desea eliminar el producto?')) {
        Delete(id);
    }
}


function Delete(objectId) {
    $.ajax(
    {
        type: "POST",
        url: $('#urlDelete').val(),
        data:
            JSON.stringify({
                id: objectId
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = "/ODSYSUI/InventoryOrders/SetMessage?id=1";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/InventoryOrders/SetMessage?id=2";
        }
    });
}


function ClearForm() {
    //Limpia los textbox
    $('#txtID').val('');
    $('#txtProjectDepartment').val('');
    $('#txtQuantity').val('');


    //Remueve todos los mensajes de error que genera el framework
    $('.field-validation-error').remove();
    $(":input").removeClass("input-validation-error");
}



function InitAutocomplete() {
    $("#txtItemFilter").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: $('#urlGetProducts').val(),
                dataType: "json",
                data: {
                    searchString: request.term,
                    IsByName: $('#rdbNameFilter').is(':checked'),
                    maxRows: 12
                },
                parse: function (data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
                    }
                    return rows;
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.code + " - " + item.name,
                            ID: item.productID,
                            ProviderID: item.providerID,
                            Code: item.code,
                            Name: item.name,
                            Cost: item.cost,
                            Price: item.price,
                            TotalPrice: item.totalPrice,
                            CurrentExistence: item.currentExistence,
                            LastPurchaseDateString: item.lastPurchaseDateString
                        }
                    }));
                },
                error: function (data, status, e) {
                    alert(e);
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            $('#productID').val(ui.item.ID);
            $('#productCode').val(ui.item.Code);
            $('#productName').val(ui.item.Name);
            $('#txtInventoryTotalValue').val(ui.item.TotalPrice);
            $('#txtLastPurchaseDate').val(ui.item.LastPurchaseDateString);
            
           
        }
    });

    $("#txtItemFilter").keyup(function () {
        if (!this.value) {
            $('#productID').val();
        }
    });
}

function AddRecord() {
    var productID = $('#productID').val();
    if (productID != '') {
        if ($("#frmInventoryOrders").valid()) {

            var item = "<li productID='" + $('#productID').val() + "' quantity='" + $('#txtQuantity').val() + "'>" +
                            "<table style='width: 100%;'>" +
                                "<tr>" +
                                    "<td style='width: 20%; text-align: left;'>" + $('#productCode').val() + "</td>" +
                                    "<td style='width: 72%; text-align: left;'>" + $('#productName').val() + "</td>" +
                                    "<td>" + $('#txtQuantity').val() + "</td>" +
                                "</tr>" +
                             "</table>" +
                             "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
                        "</li>";

            $("#InventoryOrders ul").append(item);
            Clear();

        }
    }
    else {
        alert('Debe seleccionar un producto.');
    }
}


function Add() {
    var list = new Array();
    $('#lstInventoryOrders li').each(function () {
        var current = $(this);
        var item = current.attr("productid") + ";" + current.attr("quantity");
        list.push(item);
    });
    debugger;
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlCreate").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                productLocationID: $('#cmbProductLocation').val(),
                comments: $('#txtComments').val(),
                items: list,
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                // window.location = $("#urlPrint").val();
                window.location = "/ODSYSUI/InventoryItem/SetMessage?id=3";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/InventoryItem/SetMessage?id=4";
        }
    });
}


function Edit() {
    var list = new Array();
    $('#lstInventoryOrders li').each(function () {
        var current = $(this);
        var item = current.attr("productid") + ";" + current.attr("quantity");
        list.push(item);
    });
    debugger;
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlEdit").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({           
                productLocationID: $('#cmbProductLocation').val(),
                InventoryRequisitionStatusID: $('#cmbType').val(),
                comments: $('#txtComments').val(),
                items: list,
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = "/ODSYSUI/InventoryItem/SetMessage?id=5";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/InventoryItem/SetMessage?id=6";
        }
    });
}


function Search() {
    var startDate = $('#txtStartDate').val();
    var endDate = $('#txtEndDate').val();
    var date1 = null;
  

    if (startDate != "") {
        var d1 = parseInt(startDate.substring(0, 2));
        var m1 = parseInt(startDate.substring(3, 5)) - 1;
        var y1 = parseInt(startDate.substring(6, 10));
        date1 = new Date(y1, m1, d1);
    }

    if (endDate != "") {
        var d1 = parseInt(endDate.substring(0, 2));
        var m1 = parseInt(endDate.substring(3, 5)) - 1;
        var y1 = parseInt(endDate.substring(6, 10));
        date2 = new Date(y1, m1, d1);
    }
    debugger;
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlSearch").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                startDate: date1,
                endDate: date2,
                name: $('#txtItemFilter').val(),
               
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlSearch").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            debugger;
            window.location = "/ODSYSUI/InventoryItem/SetMessage?id=2";
        }
    });
}

function Clear() {

    //var cmbProductLocation = $('#cmbProductLocation');
    //cmbProductLocation[0].selectedIndex = 0;

    //var cmbType = $('#cmbType');
    //cmbType[0].selectedIndex = 0;

    $('#txtItemFilter').val('');
    $('#productID').val('');
    $('#productCode').val('');
    $('#productName').val('');
    $('#txtQuantity').val('');
    $('#txtLastPurchaseDate').val('');
    $('#txtInventoryTotalValue').val('');

    $("#txtItemFilter").removeClass("error");
    $("#txtQuantity").removeClass("error");

    //$("#frmPrintable").find(".error").remove();
}